package org.bambrikii.site.base.persistence;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class PersistenceConnector implements IConnector {
	private Session session;
	private Transaction transaction;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.bambrikii.site.base.persistence.IConnector#openSession()
	 */
	public void openSession() {
		session = HibernateUtil.getSessionFactory().openSession();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.bambrikii.site.base.persistence.IConnector#closeSession()
	 */
	public void closeSession() {
		session.close();
	}

	public Session getSession() {
		return session;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.bambrikii.site.base.persistence.IConnector#beginTransaction()
	 */
	public void beginTransaction() throws PersistenceException {
		if (transaction != null) {
			throw new PersistenceException(
					"Close transaction before starting a new one!");
		}
		transaction = session.beginTransaction();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.bambrikii.site.base.persistence.IConnector#commitTransaction()
	 */
	public void commitTransaction() {
		transaction.commit();
		transaction = null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.bambrikii.site.base.persistence.IConnector#rollbackTransaction()
	 */
	public void rollbackTransaction() {
		transaction.rollback();
		transaction = null;
		session.close();
		session = null;
		openSession();
	}
}
